import React, { useState, useEffect } from 'react';
import { useModel } from 'umi';
import { Select, Modal } from 'antd';
import Animate from 'rc-animate';
import Farm from './components/farm';
import Insurance from './components/insurance';
import Welcome from './components/welcome';

import { fetchMapData } from './service';

import '../../assets/fonts/font.css';
import styles from './index.less';

import videoBg from '../../assets/bg.mp4';

const { Option } = Select;

let interval: NodeJS.Timer;

// 轮播间隔
const IntervalTime: number = 10 * 1000;
// 今年
const ThisYear: number = new Date().getFullYear();

const DataV: React.FC = () => {
  const [scale, setScale] = useState(1);
  const [tab, setTab] = useState(0);
  const [geoJson, setGeoJson] = useState<{ [key: string]: any }>({});
  const [year, setYear] = useState(new Date().getFullYear());

  const { initialState } = useModel('@@initialState');

  // 开启轮播
  const startInterval = () => {
    interval = setInterval(() => {
      setTab((v) => (v + 1) % 3);
    }, IntervalTime);
  };

  useEffect(() => {
    setScale(document.body.clientWidth / 1920);
    window.addEventListener('resize', () => {
      setScale(document.body.clientWidth / 1920);
    });

    startInterval();

    // 取地图数据
    const mapUrl = initialState?.currentUser?.mapUrl;
    if (mapUrl) {
      fetchMapData(mapUrl).then((response) => {
        if (response.status === 200) {
          response.json().then((data) => setGeoJson(data));
        }
      });
    }

    return () => {
      clearInterval(interval);
    };
  }, []);

  // 退出
  const logout = () => {
    initialState?.logout();
    console.log('logout');
  };

  // 编辑标题时暂停轮播
  const onWelcomEdit = (show: boolean) => {
    if (show) {
      clearInterval(interval);
    } else {
      startInterval();
    }
  };

  return (
    <div className={styles.body} style={{ transform: `scale(${scale})` }}>
      {/* 视频背景 */}
      <video
        className={styles.videoBg}
        muted={true}
        autoPlay={true}
        loop={true}
        draggable="true"
      >
        <source src={videoBg} type="video/mp4"></source>
      </video>

      {tab != 0 && (
        <>
          {/* 工具栏 */}
          <div className={styles.toolBar + ' ' + styles.layout}>
            <div className={styles.toolItem}>
              <div>
                <span>{year}年</span>{' '}
                <img src={require('../../assets/arrow.png')}></img>
              </div>
              <Select
                defaultValue={year}
                size={'large'}
                className={styles.select}
                onChange={(value) => setYear(value)}
              >
                <Option value={ThisYear}>{ThisYear}</Option>
                <Option value={ThisYear - 1}>{ThisYear - 1}</Option>
                <Option value={ThisYear - 2}>{ThisYear - 2}</Option>
              </Select>
            </div>
            <div className={styles.toolItem} onClick={logout}>
              LOGOUT
            </div>
          </div>

          {/* TAB */}
          <div
            className={`${styles.tabBar} ${styles.layout} ${
              styles['tab' + tab]
            }`}
          >
            <div
              className={`${styles.tabItem} tab==0&&${styles.active}`}
              onClick={() => {
                setTab(1);
              }}
            >
              养殖
            </div>
            <div
              className={`${styles.tabItem} tab==1&&${styles.active}`}
              onClick={() => {
                setTab(2);
              }}
            >
              保险
            </div>
          </div>
        </>
      )}

      <Animate transitionLeave={false} transitionName="fade">
        {/* 欢迎 */}
        {tab == 0 && <Welcome key={tab} onEdit={onWelcomEdit} />}
        {/* 养殖 */}
        {tab == 1 && <Farm key={tab} year={year} geoJson={geoJson} />}
        {/* 保险 */}
        {tab == 2 && <Insurance key={tab} year={year} geoJson={geoJson} />}
      </Animate>
    </div>
  );
};

export default DataV;
